<?php

namespace app\admin\controller\auth;

use app\admin\controller\Base;
use app\common\model\auth\AuthAdminModel;
use app\common\model\auth\AuthMenuModel;
use app\common\model\auth\AuthRoleModel;

class Menu extends Base
{
    /**
     * 根据账户获取权限菜单
     */
    public function getMenuByAdmin()
    {
        //获取菜单数据
        if ((new AuthAdminModel)->isAdmin($this->adminInfo)) {
            $menuData = (new AuthMenuModel)->where('type', AuthMenuModel::TYPE_MENU)
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->select()->toArray();
        } else {
            $ruleMenuData = (new AuthRoleModel)->whereIn('id', explode(',', $this->adminInfo['role_ids']))
                ->where('type', AuthMenuModel::TYPE_MENU)
                ->order(['sort' => 'DESC', 'id' => 'ASC'])
                ->field('menu_ids')
                ->select()->toArray();
            $ruleMenuIds = [];
            foreach ($ruleMenuData as $v) {
                $ruleMenuIds = array_merge($ruleMenuIds, explode(',', $v['menu_ids']));
            }
            $menuData = (new AuthMenuModel)->whereIn('id', $ruleMenuIds)->select()->toArray();
        }

        return response_success('', get_tree($menuData, 0, 'parent_id', 'son_menu'));
    }

    /**
     * 获取所有菜单树
     */
    public function getMenuTree()
    {
        $menuData = (new AuthMenuModel)->field('id,parent_id,name')
            ->order(['sort' => 'DESC', 'id' => 'ASC'])
            ->select()->toArray();
        return response_success('', get_tree($menuData, 0, 'parent_id'));
    }

}